package Task04_03;
/*
作业3

火车买票案例 (两种实现方式) : 共100张票,三个线程一起卖票,不允许出现出现负票和多卖的现象  (描述设置锁的时候要注意的事项:(Thread 和Runnable)
 */
public class Sell_02 implements Runnable{
    private int NV ; //描述火车票的票数
    public Sell_02(){}
    public Sell_02(int NV) {
        this.NV = NV;
    }

    public int getNV() {
        return NV;
    }

    public void setNV(int NV) {
        this.NV = NV;
    }
    @Override
    public void run(){ //通过其他方法调用
        otherMethods();
    }
    public void  otherMethods(){
        synchronized (oj) {
            int temp = getNV();
            if (temp < 0)
                System.out.println("请输入正确的出票数！");
            while (temp > 0){
                System.out.println("剩余票数为：" + temp +"  正在出票...");
                temp -= 1;
                if (temp == 0) {
                    System.out.println("车票已售完！");
                    setNV(temp);
                    break;
                }
            }
        }
    }
    Object oj = new Object();

    public static void main(String[] args) {
        Sell_02 sc = new Sell_02(100);

        Thread tt1 = new Thread(sc);
        Thread tt2 = new Thread(sc);
        Thread tt3 = new Thread(sc);
        tt2.start();
        tt1.start();
        tt3.start();

        try {
            tt3.join();
            tt2.join();
            tt1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}